/**
 * @Title: SmsController.java
 * @Package com.leesche.zcsp.node.web.controller.sms
 * @Description:()
 * @author dennies yang
 * @date 2016年10月20日 下午4:31:02
 * @version V1.0
 */
package com.leesche.zcsp.node.web.controller.sms;

import com.leesche.zcsp.node.app.v1.timer.VaildPhone;
import com.leesche.zcsp.node.communication.service.SmsService;
import com.leesche.zcsp.node.pay.wecha.data.Message;
import com.leesche.zcsp.node.utils.web.gernerator.MobileCodeGernerator;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.SysUser;
import com.leesche.zcsp.node.web.service.SysUserService;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Principal;
import com.leesche.zcsp.node.web.vo.Privilege;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * @author dennies yang
 * @version V1.0
 * @Title: SmsController.java
 * @Package com.leesche.zcsp.node.web.controller.sms
 * @Description:()
 * @date 2016年10月20日 下午4:31:02
 */
@Controller
@RequestMapping(value = "/sms")
public class SmsController {
    private static final Logger logger = Logger.getLogger(SmsController.class);

    @Autowired
    SmsService smsService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    private PrivilegeService privilegeService;

    /**
     * @param @param  validCode 图片验证码
     * @param @param  session
     * @param @return
     * @return Map<String,Object>
     * @throws
     * @Title: send
     * @Description: TODO(短信发送)
     */
    @ResponseBody
    @RequestMapping(value = "send", method = RequestMethod.POST)
    public Map<String, Object> send(Long userId, String validCode, HttpSession session) {
        String code = (String) session.getAttribute(Constants.LOGIN_CODE);
        if (!code.equals(validCode)) {
            return WebResult.failure("图片验证码输入错误！").toMap();
        }
        SysUser sysUser = sysUserService.selectByPrimaryKey(userId);
        //判断用户是否存在
        if (sysUser == null) {
            return WebResult.failure("用户不存在,请重新输入!").toMap();
        }

        try {

            return beginSendMsg(sysUser.getMobile(), session);

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }

    }


    /**
     * @param @param  validCode 图片验证码
     * @param @param  session
     * @param @return
     * @return Map<String,Object>
     * @throws
     * @Title: send
     * @Description: TODO(短信发送)
     */
    @ResponseBody
    @RequestMapping(value = "mobileSend", method = RequestMethod.POST)
    public Map<String, Object> sendByMobile(String mobileNum, String validCode, HttpSession session) {
        if (mobileNum == null && "".equals(mobileNum)) {
            return WebResult.failure("手机号码不能为空！").toMap();
        }

        String code = (String) session.getAttribute(Constants.LOGIN_CODE);
        if (!code.equals(validCode)) {
            return WebResult.failure("图片验证码输入错误！").toMap();
        }

        try {
            return beginSendMsg(mobileNum, session);

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }

    }

    /**
     * @Title: sendbyChangeMobile(String validCode, HttpSession session)
     * @Description: TODO(给当前用户手机发送短信验证码)
     * @author Jerry
     * @date 2016-10-29 04:26:57
     */
    @ResponseBody
    @RequestMapping(value = "sendMobileCode", method = RequestMethod.POST)
    public Map<String, Object> sendbyCurrenyUser(HttpSession session) {

        Principal principal = (Principal) session.getAttribute(Constants.LOGIN_CURRENT_USER);
        if (principal == null) {
            return WebResult.failure("用户未登录！").toMap();
        }

        try {
            SysUser sysUser = sysUserService.selectByPrimaryKey(principal.getUserid());
            return beginSendMsg(sysUser.getMobile(), session);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param mobileNum 手机号码
     * @return 发送短信结果
     * @Title: beginSendMsg(String mobileNum, HttpSession session)
     * @Description: TODO(开始发送短信)
     * @author Jerry
     * @date 2016-10-29 10:35:55
     */
    private Map<String, Object> beginSendMsg(String mobileNum, HttpSession session) throws Exception {
        //生成随机码
        String mobileCode = MobileCodeGernerator.mobileCodeGernerator();
        //发送短信
        Message<String> smsReport = smsService.sendSMS(mobileNum, mobileCode);
        //存在到session 发送成功
        if (Message.isSuccess(smsReport.getType())) {

            int maxInactiveInterval = 10;

            session.setAttribute(Constants.MOBILE_SMS_CODE, mobileCode);
            session.setAttribute(Constants.MOBILE_NUMBER, mobileNum);
            session.setMaxInactiveInterval(maxInactiveInterval * 60);

            return WebResult.success().info(Constants.getMobileCodeVaildMsg(mobileNum)).toMap();
        } else {
            return WebResult.failure("*操作太频繁，请一小时后重新申请。").toMap();
        }
        //记录短信发送内容
    }


    /**
     * @Title: sendbyChangeMobile(String validCode, HttpSession session)
     * @Description: TODO(给当前用户手机发送短信验证码)
     * @author Jerry
     * @date 2016-10-29 04:26:57
     */
    @ResponseBody
    @RequestMapping(value = "sendvaildcode", method = RequestMethod.GET)
    public Map<String, Object> sendCodebyCurrenyUser(HttpSession session) {
        try {
            //Long userid = privilegeService.getCurrentPrincipal().getUserid();
            Long userid = 1L;
            if (userid == null || userid == 0) {
                return WebResult.failure("用户未登录！").toMap();
            }else{
                String userMobile = sysUserService.selectByPrimaryKey(userid).getMobile();
                if(userMobile == null || "".equals(userMobile)){
                    return WebResult.failure("用户尚未绑定手机号。").toMap();
                }

                return this.sendMsg(userMobile, session);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    @ResponseBody
    @RequestMapping(value = "vaildcode", method = RequestMethod.GET)
    public Map<String, Object> vaildMsgMobileCode(String mobileNumber,String mobileCode, HttpSession session){
        if(mobileNumber == null || "".equals(mobileNumber)){
            //Long userid = privilegeService.getCurrentPrincipal().getUserid();
            Long userid = 1L;
            if (userid == null || userid == 0) {
                return WebResult.failure("用户未登录！").toMap();
            }else {
                String userMobile = sysUserService.selectByPrimaryKey(userid).getMobile();
                if (userMobile == null || "".equals(userMobile)) {
                    return WebResult.failure("用户尚未绑定手机号。").toMap();
                }
                mobileNumber = userMobile;
            }
        }

        String result = this.vaildCode(mobileNumber,mobileCode, session);

        return result != null ? WebResult.failure(result).toMap() : WebResult.success().toMap();

    }

    /**
     * @Title: sendMsg()
     * @Description: TODO(V2 WEB端--> 发送短信验证码)
     * @author Jerry Chan
     * @date 11:50
     */
    private Map<String, Object> sendMsg(String mobileNum, HttpSession session) throws Exception {
        //生成随机码
        String mobileCode = MobileCodeGernerator.mobileCodeGernerator();
        //发送短信
        Message<String> smsReport = smsService.sendSMS(mobileNum, mobileCode);
        //存在到session 发送成功
        if (Message.isSuccess(smsReport.getType())) {
            //有效时间
            long validTime = new Date().getTime() + (Constants.NOTIC_DEFAULT_MOBLIE_CODE_MAXINACTIVEINTERVAL * 60000);
            //保存短信验证码
            SmsVaildObject smsVaildObject = new SmsVaildObject(validTime, mobileNum);
            session.setAttribute(mobileCode + mobileNum, smsVaildObject);

            return WebResult.success().info(mobileNum).toMap();
        } else {
            String errMag = smsReport.getContent();
            if("InvalidRecNum.Malformed".equals(errMag)){
                return WebResult.failure("手机号不正确,请输入正确的手机号码").toMap();
            } else if ("InvalidSendSms".equals(errMag)){
                return WebResult.failure("获取短信过于频繁,请稍后重试").toMap();
            } else {
                return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
            }
        }
    }

    /**
     * @Title: vaildCode(String mobileNumber,String mobileCode, HttpSession session)
     * @Description: TODO( 校验短信码 )
     * @author Jerry Chan
     * @date 2016/12/15 15:12
     * @return 返回null表示校验成功
     */
    public static String vaildCode(String mobileNumber,String mobileCode, HttpSession session){
        Object obj = session.getAttribute(mobileCode+mobileNumber);
        if(obj == null){
            return "验证码错误";
        }

        SmsVaildObject vaildObject = (SmsVaildObject) obj;
        if(!mobileNumber.equals(vaildObject.getUserPhone())){
            return "手机号码错误";
        }

        if(new Date().getTime() > vaildObject.getValidTime()){
            return "验证码已过期";
        }

        return null;
    }


}
